﻿#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include "src/minet.h"
#include "minet_dev.h"

#include <QDebug>

#ifdef __cplusplus
extern "C"
{
#endif  /* __cplusplus */

typedef struct simdev_fifo
{
    uint16_t addr;
    uint8_t buf[MINET_FLEN_MAX];
    uint16_t len;
    struct simdev_fifo *next;
} simdev_fifo_t;
typedef struct
{
    int x[MINET_NODEMAX];
    int y[MINET_NODEMAX];
    minet_if_t *nif[MINET_NODEMAX];
    simdev_fifo_t *rxfifo[MINET_NODEMAX];
} simdev_t;
extern simdev_t simdev;

#ifdef __cplusplus
}
#endif  /* __cplusplus */

MiNetDev::MiNetDev(QPoint &pos, uint16_t addr, uint8_t chl)
{
    netif = new minet_if_t;
    minet_init(netif, 0, 1, addr, chl);
    minet_relay(netif, addr&1);
    simdev.x[addr] = pos.x();
    simdev.y[addr] = pos.y();
}

MiNetDev::~MiNetDev()
{
    delete netif;
}

void MiNetDev::run()
{
    time_t stamp;

    stamp = 0xFFFFFFFF;
    stamp = time(NULL) + 10;
    for (;;)
    {
		minet_loop_task(netif);
		minet_msg_t *msg = minet_recv(netif);
		if (msg != NULL) {
			int c = 30 + addr();
			char info[128];
			snprintf(info, sizeof(info), "%d recv data from %d: ", addr(), msg->addr);
			debug(msg->buf, msg->len, info);
			minet_msg_free(msg);
		}


		if (stamp < time(NULL))
		{
			char dat[16];
			minet_msg_t *msg;

			snprintf(dat, sizeof(dat), "%d", stamp % 10000);
			msg = (minet_msg_t*) minet_msg_malloc(strlen(dat));
			msg->addr = MINET_ADDR_GW;
			memcpy(msg->buf, dat, strlen(dat));
			msg->len = strlen(dat);
			minet_send(netif, msg);
			minet_msg_free(msg);
			stamp = time(NULL) + 5;
		}

		msleep(1);
    }
}

void MiNetDev::posUpdate(QPoint &pos)
{
    this->pos = pos;
    simdev.x[netif->addr] = pos.x();
    simdev.y[netif->addr] = pos.y();
}

QPoint MiNetDev::posGet()
{
    return pos;
}

uint16_t MiNetDev::addr()
{
    return netif->addr;
}

void MiNetDev::debug(uint8_t *buf, int len, char *info)
{
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    printf("\033[44m\033[33m%d-%02d-%02dT%02d:%02d:%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
    if (info != NULL)
        printf(" %s", info);
    int c = 30 + addr();
    printf(" [", c);
    for (int i = 0; i < len; ++i) {
        printf("%02X ", buf[i]);
    }
    printf("]\n");
    printf("\033[0m");
    fflush(stdout);
}
